package com.bs.visitservice.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bs.visitservice.entity.Comment;
import com.bs.visitservice.entity.CommentPhoto;
import com.bs.visitservice.entity.OrderInfo;
import com.bs.visitservice.entity.UserInfo;
import com.bs.visitservice.service.CommentPhotoService;
import com.bs.visitservice.service.CommentService;
import com.bs.visitservice.service.OrderInfoService;
import com.bs.visitservice.service.UserInfoService;
import com.bs.visitservice.utils.Result;
import com.bs.visitservice.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private CommentPhotoService commentPhotoService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private UserInfoService userInfoService;
    @RequestMapping("/userpublic/querySellerComments")
    public Result querySellerComments(@RequestBody Map cond){
        Map<String,Object> result = new HashMap<>();
        List<Map<String, Object>> sellerComments = commentService.querySellerComments(cond);
        cond.remove("pageIndex");
        int count = commentService.querySellerComments(cond).size();
        sellerComments.forEach(map->{
            Long no = (Long)map.get("no");
            LambdaQueryWrapper<CommentPhoto> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommentPhoto::getCommentNo,no).orderByAsc(CommentPhoto::getSn);
            List<Map<String, Object>> photoList = commentPhotoService.listMaps(wrapper);
            map.put("photos",photoList);
            Object ono =  map.get("orderNo");
            Long un = null;
            if(ono != null){
                String orderNo = (String)ono;
                LambdaQueryWrapper<OrderInfo> oWrapper = new LambdaQueryWrapper<>();
                oWrapper.eq(OrderInfo::getOrderNo,orderNo);
                OrderInfo oi = orderInfoService.getOne(oWrapper);
                un = oi.getUserNo();
            }
            if(un != null){
                UserInfo userInfo = userInfoService.getById(un);
                map.put("account",userInfo.getNickname());
                map.put("avatarUrl",userInfo.getAvatarUrl());
            }
        });
        result.put("total",count);
        result.put("datas",sellerComments);
        return Result.success(result);
    }
    /**
     * 添加评论
     * @param cond
     * @return
     */
    @Transactional
    @RequestMapping(value = "/user/saveComment",method = RequestMethod.POST)
    public Result saveComment(@RequestBody Map cond){
        Comment comment = (Comment)ResultUtil.transObject(cond,Comment.class);
        Long orderNo = comment.getOrderNo();
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper();
        wrapper.set(OrderInfo::getOrderStatus,"7");
        wrapper.eq(OrderInfo::getNo,orderNo);
        orderInfoService.update(wrapper);
        comment.setDataTime(new Date());
        boolean isSuc = commentService.save(comment);
        List<Map<String,Object>> reses = new ArrayList<>();
        Map<String,Object> res = new HashMap<>();
        res.put("commentNo",comment.getNo());
        reses.add(res);
        if(isSuc){
            return Result.success(reses);
        }
        return Result.error(null);
    }

    /**
     * 上传评论图片
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/saveCommentPhoto",method = RequestMethod.POST)
    public Result saveCommentPhoto(HttpServletRequest request){
        boolean isSuc = false;
        InputStream is = null;
        try {
            request.setCharacterEncoding("utf-8"); //设置编码
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formdata的值
            Iterator<String> iterator = req.getFileNames();
            Map<String, String[]> parameterMap = req.getParameterMap();
            Map<String,Object> transMap = new HashMap<>();
            parameterMap.forEach((k,v)->{
                transMap.put(k,v[0]);
            });
            CommentPhoto c = (CommentPhoto)ResultUtil.transObject(transMap, CommentPhoto.class);
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                is = file.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[2048];
                int len = 0;
                while ((len = is.read(bytes))>0){
                    bos.write(bytes, 0,len);
                }
                byte[] res = bos.toByteArray();
                c.setPhoto(res);
            }
            isSuc = commentPhotoService.save(c);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(isSuc){
            Result.success(null);
        }
        return Result.error(null);
    }
}
